-- Advance: if we want to check that the spell will be ready
-- in a specific peroid of time. Nil if we check the spell's
-- cooldown time has ended. In seconds
function TMacros:SpellReady(SpellName, Advanced)
	local spell, rank = GetSpellInfo(SpellName, BOOKTYPE_SPELL)
	local id = GetSpellIndex(spell, rank)
	local wait, now, s, d = Advanced or 0, GetTime(), GetSpellCooldown(id, BOOKTYPE_SPELL)
	return s == 0 or s + d < now + wait
end

-- Simulate cast spell with secure options
-- This function performs like cast [@mouseover,help,exists,nodead][@target,help,exist,nodead][@player] SpellName,
-- but with the following parameters:
-- Friend: if not nil, this spell wants to target a friend; enemy otherwise.
-- AutoSelect: if is not nil, a nearest friend or enemy will be select if no
-- mouseover or target unit is found.
function TMacros:CastSpellOptionTarget(Spell, Friend, AutoSelect)
    local targetFunc = nil
    local unit = nil
    local newTarget = nil

    if Friend then
        targetFunc = self.UnitIsAliveFriend
    else
        targetFunc = self.UnitIsAliveEnemy
    end

    if not unit and targetFunc(self, "mouseover") then
        unit = "mouseover"
        if not UnitIsUnit(unit, "target") then
            newTarget = true
        end
    end

    if not unit and targetFunc(self, "target") then 
        unit = "target"
    end

    if not unit and AutoSelect then
        if Friend then 
            unit = "player"
            if not UnitIsUnit(unit, "target") then
                newTarget = true
            end
        else 
            TargetNearestEnemy()
		    unit = "target"
        end
    end

    if unit then
        TargetUnit(unit)
		CastSpellByName(Spell)
	end

    if newTarget then
        TargetLastTarget()
    end
end